import { NextRequest, NextResponse } from 'next/server';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

// Cloudflare R2 配置
const R2_ACCESS_KEY_ID = '19a1bec41ffc3c4fd99c147b8d07ac2c';
const R2_SECRET_ACCESS_KEY = 'b3b192e9a9e52b400ee5377977f0cdd68d3515b083f520af1f144895efdaa095';
const R2_BUCKET_NAME = 'xian-shan-ba-jun'; // 請替換為您的實際 bucket 名稱
const R2_PUBLIC_URL = 'https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev';

// 您需要從 Cloudflare 儀表板獲取正確的 Account ID
// 這不是 Access Key ID，而是您的 Cloudflare Account ID
const R2_ACCOUNT_ID = '7ed6051b944ee6a218f0fdaf771b4789'; // 請從 Cloudflare 儀表板右側獲取

// 初始化 S3 客戶端（用於 R2）
const s3Client = new S3Client({
  region: 'auto',
  endpoint: `https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: R2_ACCESS_KEY_ID,
    secretAccessKey: R2_SECRET_ACCESS_KEY,
  },
  forcePathStyle: true,
});

// 生成唯一文件名
function generateUniqueFileName(originalName: string): string {
  const timestamp = Date.now();
  const randomString = Math.random().toString(36).substring(2, 15);
  const extension = originalName.split('.').pop();
  return `${timestamp}-${randomString}.${extension}`;
}

// 驗證文件類型
function isValidFileType(file: File): boolean {
  const allowedTypes = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/webp',
    'application/pdf',
    'text/plain',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  ];
  return allowedTypes.includes(file.type);
}

// 驗證文件大小（最大 10MB）
function isValidFileSize(file: File): boolean {
  const maxSize = 10 * 1024 * 1024; // 10MB
  return file.size <= maxSize;
}

/**
 * @swagger
 * /api/upload:
 *   post:
 *     tags:
 *       - File Upload
 *     summary: 上傳文件到 Cloudflare R2
 *     description: 上傳文件到 Cloudflare R2 對象存儲，支持圖片、PDF、文檔等格式
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *                 description: 要上傳的文件
 *               folder:
 *                 type: string
 *                 description: 可選的文件夾路徑
 *                 example: "images"
 *             required:
 *               - file
 *     responses:
 *       200:
 *         description: 文件上傳成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 message:
 *                   type: string
 *                   example: "文件上傳成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     url:
 *                       type: string
 *                       example: "https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/images/1703123456789-abc123def456.jpg"
 *                     fileName:
 *                       type: string
 *                       example: "1703123456789-abc123def456.jpg"
 *                     originalName:
 *                       type: string
 *                       example: "photo.jpg"
 *                     size:
 *                       type: number
 *                       example: 1024000
 *                     type:
 *                       type: string
 *                       example: "image/jpeg"
 *       400:
 *         description: 請求錯誤
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "未找到文件或文件格式不支持"
 *       413:
 *         description: 文件過大
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "文件大小超過限制（最大 10MB）"
 *       500:
 *         description: 服務器錯誤
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "文件上傳失敗"
 *                 error:
 *                   type: string
 *                   example: "詳細錯誤信息"
 */
export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const folder = formData.get('folder') as string || '';

    // 驗證文件是否存在
    if (!file) {
      return NextResponse.json(
        {
          success: false,
          message: '未找到文件',
        },
        { status: 400 }
      );
    }

    // 驗證文件類型
    if (!isValidFileType(file)) {
      return NextResponse.json(
        {
          success: false,
          message: '不支持的文件格式',
        },
        { status: 400 }
      );
    }

    // 驗證文件大小
    if (!isValidFileSize(file)) {
      return NextResponse.json(
        {
          success: false,
          message: '文件大小超過限制（最大 10MB）',
        },
        { status: 413 }
      );
    }

    // 生成唯一文件名
    const fileName = generateUniqueFileName(file.name);
    const key = folder ? `${folder}/${fileName}` : fileName;

    // 將文件轉換為 Buffer
    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    // 上傳到 R2
    const uploadCommand = new PutObjectCommand({
      Bucket: R2_BUCKET_NAME,
      Key: key,
      Body: buffer,
      ContentType: file.type,
      ContentLength: file.size,
    });

    await s3Client.send(uploadCommand);

    // 構建公共 URL
    const publicUrl = `${R2_PUBLIC_URL}/${key}`;

    return NextResponse.json({
      success: true,
      message: '文件上傳成功',
      data: {
        url: publicUrl,
        fileName: fileName,
        originalName: file.name,
        size: file.size,
        type: file.type,
        key: key,
      },
    });

  } catch (error) {
    console.error('文件上傳錯誤:', error);
    return NextResponse.json(
      {
        success: false,
        message: '文件上傳失敗',
        error: error instanceof Error ? error.message : '未知錯誤',
      },
      { status: 500 }
    );
  }
}

/**
 * @swagger
 * /api/upload:
 *   get:
 *     tags:
 *       - File Upload
 *     summary: 獲取上傳配置信息
 *     description: 獲取文件上傳的配置信息，包括支持的文件類型和大小限制
 *     responses:
 *       200:
 *         description: 成功獲取配置信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: object
 *                   properties:
 *                     maxFileSize:
 *                       type: string
 *                       example: "10MB"
 *                     supportedTypes:
 *                       type: array
 *                       items:
 *                         type: string
 *                       example: ["image/jpeg", "image/png", "image/gif", "image/webp", "application/pdf", "text/plain"]
 *                     endpoint:
 *                       type: string
 *                       example: "/api/upload"
 */
export async function GET() {
  return NextResponse.json({
    success: true,
    data: {
      maxFileSize: '10MB',
      supportedTypes: [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'application/pdf',
        'text/plain',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      ],
      endpoint: '/api/upload',
    },
  });
}